/**
 * $Id$
 *
 * Unpublished Work Copyright 2013 Confirmit, Inc. All Rights Reserved.
 *
 * Last changed by $Author$
 * Last changed at $Date$
 */
package com.youtills.core.app.dev;

import com.youtills.core.app.common.ISiteLayout;
import com.youtills.core.app.common.SiteLayout;
import com.youtills.core.lang.StringUtil;
import com.youtills.core.random.RandomGenerator;
import com.youtills.core.random.RandomString;
import com.youtills.core.web.IRequestHandler;
import org.apache.commons.codec.binary.Base64;

/**
 * TODO
 *
 * @author Ravi Kumar Chiluveru (RaviC)
 * @since 12.2, (7/10/13 5:17 PM)
 */
public class RandomRequestHandler extends SiteLayout implements IRequestHandler, ISiteLayout {

    public String getMainContentPage() {
        return "/WEB-INF/jsp/dev/random.jsp";
    }


    public String getType(){
        return getContextBean().getRequest().getParameter("type");
    }

    public int getLength(){
        return StringUtil.getNumber(getContextBean().getRequest().getParameter("length"), 0).intValue();
    }

    public String getResult(){
        String result = "";

        String action = getContextBean().getRequest().getParameter("action");
        String type = getType();

        int length = getLength();

        if(!StringUtil.isEmpty(action) && !StringUtil.isEmpty(type)){
            try{

                if(length > 0 && length < 100000){
                    if("bytes".equals(type)){
                        byte[] bytes = RandomGenerator.generateRandomBytes(length);
                        result = new String(Base64.encodeBase64(bytes));
                    }else if ("string".equals(type)){
                        result = RandomString.getInstance().getNext(length);
                    }
                } else {
                    result = "Invalid length=" + getContextBean().getRequest().getParameter("length") +".  Value must be between 1 & 99999";
                }
            }catch (Exception e){
                result = "Exception " + e.getMessage();
            }

        }
        return result;
    }

}